package cn.deschen.eshop.auth.filter;

import cn.deschen.eshop.auth.properties.JwtProperties;
import cn.deschen.eshop.auth.properties.SecurityProperties;
import cn.deschen.eshop.auth.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.SecurityContext;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author hanbin_chen
 * @Description jwt认证过滤器
 * @DateTime 2021/1/19 17:03
 * @Version V1.0.0
 */
@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(
            HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        log.info("【权限模块】请求路径url = {}", request.getRequestURI());
        JwtProperties jwt = securityProperties.getJwt();
        // 从请求头中获取认证信息, 内容 格式：“Bear token”
        String authHeader = request.getHeader(jwt.getTokenHeader());
        // 判断请求头信息是否存在且其中token是否存在
        if (null != authHeader && authHeader.startsWith(jwt.getTokenHead())) {
            // 获取token信息
            String authToken = authHeader.substring(jwt.getTokenHead().length());
            String userName = jwtTokenUtil.getUserNameFromToken(authToken);
            // 判断用户名是否第一次登入
            if (!StringUtils.isEmpty(userName) && null == SecurityContextHolder.getContext().getAuthentication()) {
                UserDetails userDetails = userDetailsService.loadUserByUsername(userName);
                // 判断token是否有效
                if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                    //获取用户的信息及权限
                    UsernamePasswordAuthenticationToken authentication =
                            new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    // 存储用户信息
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }

        filterChain.doFilter(request, response);

    }
}
